package cn.lzy.demo;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;

/**
 * @Description
 * @Author lzy
 * @Date 2023/12/27 23:00
 * @Version
 **/
@Configuration
@ComponentScan
@PropertySource("classpath:db.properties")
public class JavaConfig {

    @Value("${db.username}")
    private String username;

    @Value("${db.password}")
    private String password;

    @Value("${db.url}")
    private String url;



    @Bean
    DataSource dataSource() {
        DruidDataSource ds = new DruidDataSource();
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }


    @Bean
    JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(dataSource());
    }


    /**
     * 配置事务管理器
     * @return
     */
    @Bean
    PlatformTransactionManager platformTransactionManager() {
        // PlatformTransactionManager是一个接口，所以提供的是它的实现类
        // 由于使用的是关系型数据库，因此这里提供 DataSourceTransactionManager
        return new DataSourceTransactionManager(dataSource());
    }


    @Bean
    TransactionTemplate transactionTemplate() {
        return new TransactionTemplate(platformTransactionManager());
    }
}
